package pers.cz.controller;

import pers.cz.excel.PoiUtils;
import pers.cz.model.TestCase;
import pers.cz.pub.RespBean;
import pers.cz.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文档上传下载接口
 * @program: PostGirl-panent
 * @description: FileUploadController
 * @author: Cheng Zhi
 * @create: 2021-03-09 19:49
 **/
@RestController
@Api(tags = "文件上传下载接口")
@RequestMapping("/api/fileUploadAndDownload")
public class FileUploadController {

    @Autowired
    FileUploadService fileUploadService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传（只支持Excel）")
    @PostMapping("/upload")
    public RespBean upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        int userId = Integer.valueOf(request.getAttribute("userId").toString());
        int count = 0;
        // 上传文件入库
        count = fileUploadService.upload(file, userId);

        return RespBean.ok("上传成功",count);
    }

    /**
     * 文件导出
     * @return
     */
    @ApiOperation(value = "文件导出")
    @GetMapping("/download")
    public String download() {

        TestCase test = new TestCase();
        List<TestCase> testList = new ArrayList<>();
        testList.add(test);
        ResponseEntity<byte[]> responseEntity = PoiUtils.exportToExcel(testList);
        String filename = responseEntity.getHeaders().getContentDisposition().getFilename();
        String out = null;
        try {
            byte[] body = responseEntity.getBody();
            out = new BASE64Encoder().encode(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * 文件导出
     * @return
     */
    @ApiOperation(value = "文件导出不加密")
    @GetMapping("/downloadNo")
    public String downloadNo() {

        TestCase test = new TestCase();
        List<TestCase> testList = new ArrayList<>();
        testList.add(test);
        ResponseEntity<byte[]> responseEntity = PoiUtils.exportToExcel(testList);
        String filename = responseEntity.getHeaders().getContentDisposition().getFilename();
        String out = null;
        try {
            byte[] body = responseEntity.getBody();
            out=new String(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * 测试导出zip文件
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "测试导出zip")
    @PostMapping("/downloadZip")
    public String downloadZip() throws IOException {

        ByteArrayOutputStream byteOutPutStream = new ByteArrayOutputStream();
        // 创建一个集合用于 压缩打包的参数
        List<Map<String, String>> parms = new ArrayList<>();
        // 创建一个map集合
        Map<String, String> fileMaps = new HashMap<>();
        fileMaps.put("filePath", "D:\\test");
        fileMaps.put("fileName", "cz.txt");
/*        Map<String, String> fileMaps1 = new HashMap<>();
        fileMaps1.put("filePath", "D:\\test");
        fileMaps1.put("fileName", "zz.txt");*/
        // 放入集合
        parms.add(fileMaps);
        //parms.add(fileMaps1);
        this.batchFileToZip(parms, byteOutPutStream);

        String zipName = "成智.zip";
        HttpHeaders headers = new HttpHeaders();
        try {
            zipName = new String(zipName.getBytes("GBK"), "ISO-8859-1");
            //zipName = new String(zipName.getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", zipName);// 文件名称

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteOutPutStream.toByteArray(), headers, HttpStatus.CREATED);
        String filename = responseEntity.getHeaders().getContentDisposition().getFilename();
        String out = null;
        try {
            byte[] body = responseEntity.getBody();
            out = new BASE64Encoder().encode(body);
            //String name = "成智是个好孩子123abcdefghi";
            //byte[] bb = name.getBytes("UTF-8");
            //out = new BASE64Encoder().encode(bb);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(out);

        // 解密
        //decrypt(out);
        //return responseEntity;
        return out;
    }

    private void decrypt(String result) throws IOException {

        FileOutputStream fos = new  FileOutputStream("D:\\test\\ktt.zip");
        fos.write(new BASE64Decoder().decodeBuffer(result));
        fos.close();

    }
    private void batchFileToZip(List<Map<String, String>> params, ByteArrayOutputStream byteOutPutStream) throws IOException {

        ZipOutputStream zipOut = new ZipOutputStream(byteOutPutStream);
        try {
            for (Map<String, String> map : params) {

                String fileName = map.get("fileName");
                String filePath = map.get("filePath");
                ZipEntry zipEntry = new ZipEntry(fileName);
                File file = new File(filePath + "/" + fileName);
                byte[] fileByte = getBytes(file);
                FileOutputStream outputStream = new FileOutputStream(file);
                zipOut.putNextEntry(zipEntry);
                zipOut.write(fileByte);
                zipOut.closeEntry();
            }
        } finally {
            zipOut.close();
        }
    }

    private byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
